package com.atguigu.stuty.base;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类，面向对象编程，对象 = 属性 + 方法
 */
class Ticket {
    private int number = 100;

    // 普通方法添加 synchronized 关键字
    /*public synchronized void sale() {
        if(number > 0) {
            System.out.println(Thread.currentThread().getName() + "出售了第：" + (number--) + "张票，剩余：" + number + "张票");
        }
    }*/
    // ReentrantLock 叫做重入锁 + 默认悲观锁 + 默认公平锁
    // ReentrantLock 添加 true 为公平锁
    // private final Lock lock = new ReentrantLock(true);
    private final Lock lock = new ReentrantLock();
    public void sale() {
        while (number > 0) {
            lock.lock();
            try {
                if(number > 0) {
                    System.out.println(Thread.currentThread().getName() + "出售了第：" + (number--) + "张票，剩余：" + number + "张票");
                }
            } finally {
                lock.unlock();
            }
        }
    }
}




/**
 * @Author early morning
 * @Create 2025/4/22 19:38
 * @Description: 三个售票员出售100张票
 * juc小口诀第一式
 * 1 在高内聚低耦合前提下，    线程    操作   资源类
 */
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        /**
         * new Thread 中为 Lomda，是 Runnable 接口的实现类
         * new Thread(new Runnable()
         *         {
         *             @Override
         *             public void run()
         *             {
         *                 for (int i = 1; i <= 50; i++) {
         *                     ticket.sale();
         *                 }
         *             }
         *         }, "A").start();
         *  以下是简写形式
         */
        new Thread(()->{
            ticket.sale();
        },"金莲").start();

        new Thread(()->{
            ticket.sale();
        },"冰冰").start();
        new Thread(()->{
            ticket.sale();
        },"柳岩").start();

    }
}
